package com.iye.puretennis.custom;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import com.iye.puretennis.LoginActivity;
import com.iye.puretennis.R;
import com.iye.puretennis.domain.CacheType;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.DBManager;
import com.iye.puretennis.helper.ImageHelper;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.utils.StringUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import java.io.File;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/9
 * Time: 13:42
 */
public class BaseActivity extends Activity {

    private long exitTime = 0;

    protected DBManager dbManager;

    protected UserToken token;

    protected Typeface defaultTypeface;

    protected String registrationID;

    protected int width;

    protected int height;


    protected DisplayImageOptions.Builder builder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        width = dm.widthPixels;

        height = dm.heightPixels;

        dbManager = new DBManager(this);

        token = dbManager.retrieveCurrentUser();

        CustomApplication application = (CustomApplication) getApplication();

        defaultTypeface = application.getHuaWenHuPo();

        final String userDevice = CacheType.USER_DEVICE.name();

        registrationID = dbManager.retrieveMyCachedData(userDevice);

        if (!StringUtils.hasText(registrationID) && token != null) {

            registrationID = JPushInterface.getRegistrationID(getApplicationContext());

            dbManager.cacheMyData(userDevice, registrationID);
        }

        builder = ImageHelper.createImageBuilder();

        ExitApplication.getInstance().addActivity(this);

    }

    //log out the system
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            exitApp();
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }


    public void exitApp() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(this, getString(R.string.exit_system), Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            if (hasNetWork()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        if(ServerAccessHelper.logout(token.getToken(), registrationID)){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ExitApplication.getInstance().exit();

                                }
                            });
                        }
                    }
                }).start();
            } else {
                ExitApplication.getInstance().exit();

            }
        }
    }

    private void logout() {
        dbManager.logout();
        ExitApplication.getInstance().exit();
    }

    protected boolean hasNetWork() {
        ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        cwjManager.getActiveNetworkInfo();

        return cwjManager.getActiveNetworkInfo() != null && cwjManager.getActiveNetworkInfo().isAvailable();

    }

    @Override
    protected void onResume() {

        super.onResume();

        JPushInterface.onResume(this);

    }

    @Override
    protected void onPause() {

        super.onPause();

        JPushInterface.onPause(this);

    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
